<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
// 导入消息工具
import message from "@/utils/message.js";
// 导入图标工具
import { ArrowLeft, View, Delete } from "@/utils/icons.js";
import { getSubmittedResumes, cancelResumeSubmit } from "@/api/resume";

const router = useRouter();
const store = useStore();

// 投递记录列表
const submissionList = ref<any[]>([]);

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});

// 状态过滤
const statusFilter = ref("");

// 状态选项
const statusOptions = [
    { value: "", label: "全部状态" },
    { value: "0", label: "待查看" },
    { value: "1", label: "已查看" },
    { value: "2", label: "已面试" },
    { value: "3", label: "不合适" },
    { value: "4", label: "已通过" },
];

// 获取投递记录
const getSubmissionHistory = async () => {
    loading.value = true;
    try {
        const params = {
            page: pagination.currentPage,
            size: pagination.pageSize,
            status: statusFilter.value,
        };

        const response = await getSubmittedResumes(params);
        if (response.code === 200 || response.code === 0) {
            submissionList.value = response.data.list || response.data || [];
            pagination.total = response.data.total || submissionList.value.length;
        } else {
            message.error("获取投递记录失败");
        }

        // 如果没有真实数据，使用模拟数据
        if (submissionList.value.length === 0) {
            submissionList.value = getMockData();
            pagination.total = submissionList.value.length;
        }
    } catch (error) {
        console.error("获取投递记录失败", error);
        message.error("获取投递记录失败");
        // 使用模拟数据
        submissionList.value = getMockData();
        pagination.total = submissionList.value.length;
    } finally {
        loading.value = false;
    }
};

// 生成模拟数据
const getMockData = (): any[] => {
    return [
        {
            id: "1",
            resume_id: "1",
            resume_title: "前端开发工程师简历",
            job_id: "1",
            job_title: "前端开发工程师",
            company_name: "科技有限公司",
            submit_time: "2025-05-10T10:30:00",
            status: "1",
            status_text: "已查看",
            feedback: "",
        },
        {
            id: "2",
            resume_id: "1",
            resume_title: "前端开发工程师简历",
            job_id: "4",
            job_title: "Vue开发工程师",
            company_name: "软件科技有限公司",
            submit_time: "2025-05-08T14:20:00",
            status: "2",
            status_text: "已面试",
            feedback: "面试通过，等待HR面试",
        },
        {
            id: "3",
            resume_id: "2",
            resume_title: "实习生应聘简历",
            job_id: "3",
            job_title: "资深前端开发",
            company_name: "网络科技有限公司",
            submit_time: "2025-05-05T09:15:00",
            status: "3",
            status_text: "不合适",
            feedback: "与岗位要求不匹配",
        },
        {
            id: "4",
            resume_id: "3",
            resume_title: "校园招聘简历模板",
            job_id: "5",
            job_title: "全栈开发工程师",
            company_name: "科技有限公司",
            submit_time: "2025-05-01T16:40:00",
            status: "0",
            status_text: "待查看",
            feedback: "",
        },
        {
            id: "5",
            resume_id: "2",
            resume_title: "实习生应聘简历",
            job_id: "2",
            job_title: "Web前端工程师",
            company_name: "互联网科技公司",
            submit_time: "2025-04-28T11:30:00",
            status: "4",
            status_text: "已通过",
            feedback: "恭喜通过所有面试，请等待offer",
        },
    ];
};

// 查看简历详情
const viewResume = (resumeId: string) => {
    router.push({
        path: "/user/resumeInfo",
        query: { id: resumeId },
    });
};

// 查看职位详情
const viewJob = (jobId: string) => {
    router.push({
        path: "/job/detail",
        query: { id: jobId },
    });
};

// 取消投递
const cancelSubmission = async (id: string, index: number) => {
    try {
        const response = await cancelResumeSubmit(id);
        if (response.code === 200 || response.code === 0) {
            message.success("已取消投递");
            submissionList.value.splice(index, 1);
            if (submissionList.value.length === 0) {
                getSubmissionHistory();
            }
        } else {
            message.error(response.message || "取消投递失败");
        }
    } catch (error) {
        console.error("取消投递失败", error);
        message.error("取消投递失败");
    }
};

// 格式化日期
const formatDate = (dateStr: string): string => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    return date.toLocaleString();
};

// 状态对应的class
const getStatusType = (status: string): string => {
    const statusMap: Record<string, string> = {
        "0": "info",
        "1": "primary",
        "2": "warning",
        "3": "danger",
        "4": "success",
    };
    return statusMap[status] || "info";
};

// 页码变化
const handleCurrentChange = (currentPage: number) => {
    pagination.currentPage = currentPage;
    getSubmissionHistory();
};

// 每页条数变化
const handleSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.currentPage = 1;
    getSubmissionHistory();
};

// 状态筛选变化
const handleStatusChange = () => {
    pagination.currentPage = 1;
    getSubmissionHistory();
};

// 返回
const goBack = () => {
    router.go(-1);
};

onMounted(() => {
    getSubmissionHistory();
});
</script>

<template>
    <div class="history-container" v-loading="loading">
        <div class="page-header">
            <div class="left-section">
                <el-button link @click="goBack" :icon="ArrowLeft">返回</el-button>
                <h2>投递历史</h2>
            </div>
            <div class="filter-section">
                <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleStatusChange">
                    <el-option
                        v-for="item in statusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
        </div>

        <!-- 投递记录列表 -->
        <div class="history-list">
            <el-card v-for="(item, index) in submissionList" :key="item.id" class="history-item">
                <div class="item-header">
                    <div class="job-info">
                        <h3 class="job-title" @click="viewJob(item.job_id)">{{ item.job_title }}</h3>
                        <div class="company-name">{{ item.company_name }}</div>
                    </div>
                    <el-tag :type="getStatusType(item.status)" size="small">{{ item.status_text }}</el-tag>
                </div>

                <div class="item-content">
                    <div class="info-row">
                        <span class="label">投递简历：</span>
                        <span class="value resume-title" @click="viewResume(item.resume_id)">
                            {{ item.resume_title }}
                        </span>
                    </div>
                    <div class="info-row">
                        <span class="label">投递时间：</span>
                        <span class="value">{{ formatDate(item.submit_time) }}</span>
                    </div>
                    <div v-if="item.feedback" class="info-row">
                        <span class="label">反馈：</span>
                        <span class="value feedback">{{ item.feedback }}</span>
                    </div>
                </div>

                <div class="item-footer">
                    <el-button size="small" @click="viewResume(item.resume_id)" :icon="View" text> 查看简历 </el-button>
                    <el-button
                        v-if="item.status === '0'"
                        size="small"
                        type="danger"
                        @click="cancelSubmission(item.id, index)"
                        :icon="Delete"
                        text
                    >
                        取消投递
                    </el-button>
                </div>
            </el-card>

            <!-- 空状态 -->
            <el-empty v-if="submissionList.length === 0" description="暂无投递记录">
                <el-button type="primary" @click="router.push('/jobList')">浏览职位</el-button>
            </el-empty>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pagination.pageSize"
                :current-page="pagination.currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<style scoped>
.history-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.left-section {
    display: flex;
    align-items: center;
}

.left-section h2 {
    margin: 0 0 0 10px;
}

.history-item {
    margin-bottom: 15px;
}

.item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
}

.job-title {
    margin: 0;
    font-size: 18px;
    color: #409eff;
    cursor: pointer;
}

.job-title:hover {
    text-decoration: underline;
}

.company-name {
    margin-top: 5px;
    font-size: 14px;
    color: #606266;
}

.item-content {
    margin-bottom: 15px;
}

.info-row {
    margin-bottom: 8px;
}

.label {
    color: #909399;
    width: 80px;
    display: inline-block;
}

.resume-title {
    color: #409eff;
    cursor: pointer;
}

.resume-title:hover {
    text-decoration: underline;
}

.feedback {
    color: #e6a23c;
}

.item-footer {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #ebeef5;
    padding-top: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

@media screen and (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .filter-section {
        margin-top: 10px;
        width: 100%;
    }

    .filter-section .el-select {
        width: 100%;
    }

    .item-header {
        flex-direction: column;
    }

    .item-header .el-tag {
        margin-top: 10px;
    }
}
</style>
